<template>
    <!-- 文件单张多张上传 -->
    <div class="wrap-upload">
        <el-upload ref="upload" class="file-uploader" :class="{ limited: uploadLimited }" :action="domain" :data="uploadData" list-type="text" :file-list="uploadShowFileList" :limit="limitNum" :before-upload="beforeUpload" :on-success="uploadSuccess" :on-error="uploadError" :on-exceed="uploadExceed" :on-preview="uploadPreview" :on-remove="uploadRemove" :disabled="disabled">
            <el-button type="primary" class="upload-btn">点击上传</el-button>
        </el-upload>
    </div>
</template>

<script>
import uploadMixin from './mixin.js';
import { genNonDuplicateID } from '@/utils/index.js';
export default {
    name: 'uploadFile',
    mixins: [uploadMixin],
    props: {
        // 是否禁用
        disabled: {
            type: Boolean,
            default: false
        },
        // 对应的表单键名
        formKey: {
            required: true,
            type: String
        },
        // 上传后的图片
        uploadedUrl: {
            type: String,
            default: ''
        },
        // 限制上传数量
        limitNum: {
            type: Number,
            default: 1
        },
        // 限制上传大小
        limitSize: {
            type: Number,
            default: 5
        }
    },
    data() {
        return {
            // 上传的文件列表 {name: '',url: ''}
            uploadShowFileList: [],
            // 上传是否超过限制
            uploadLimited: false
        }
    },
    methods: {
        // 上传前
        beforeUpload(file) {
            // 允许上传的文件类型
            const allowFileFormat = ['text/html', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/png', 'image/jpeg', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
            const isAllowFile = allowFileFormat.some(item => {
                return file.type === item
            })
            const isLimitSize = file.size / 1024 / 1024 < this.limitSize;
            if (!isAllowFile) {
                this.$message_tip('上传文件格式不支持', 'error')
            }
            if (!isLimitSize) {
                this.$message_tip(`上传文件大小不能超过${this.limitSize}MB!`, 'error')
            }
            this.uploadData.key = genNonDuplicateID() + '|' + file.name
            return isAllowFile && isLimitSize;
        },
        // 上传成功
        uploadSuccess(res, file, fileList) {
            let uploadFileList = fileList.map(item => {
                if (item.hasOwnProperty('response')) {
                    return `${this.qiniuUrl}/${item.response.key}`
                } else {
                    return item.url
                }
            })
            this.$emit('update-form', this.formKey, uploadFileList.join(','))
        },
        // 超出
        uploadExceed(files, fileList) {
            this.$message_tip(`最多可上传${this.limitNum}份文件`, 'error')
        },
        // 上传失败
        uploadError(err, file) {
            this.$message_tip('文件上传失败,请稍后重试！', 'error')
        },
        // 删除
        uploadRemove(file, fileList) {
            let uploadFileList = fileList.map(item => {
                if (item.hasOwnProperty('response')) {
                    return `${this.qiniuUrl}/${item.response.key}`
                } else {
                    return item.url
                }
            })
            this.$emit('update-form', this.formKey, uploadFileList.join(','))
        },
        // 上传预览
        uploadPreview(file) {
            let url = file.hasOwnProperty('response') ? file.response.data : file.url
            window.open(url)
        }
    },
    mounted() {
        // 已上传文件回显
        if (!this.uploadedUrl) return
        this.uploadShowFileList = this.uploadedUrl.split(',').map(item => {
            return {
                name: getFileName(item),
                url: item
            }
        })
        this.uploadLimited = this.uploadShowFileList.length >= this.limitNum ? true : false
    },
    watch: {
        'uploadedUrl': function (newVal, oldVal) {
            // 父组件uploadedUrl
            let uploadedList = newVal ? newVal.split(',') : []
            this.uploadLimited = uploadedList.length >= this.limitNum ? true : false
            // 父组件uploadedUrl变化 - 取出已存的上传list
            let uploadFileList = this.$refs.upload.uploadFiles.map(item => {
                if (item.hasOwnProperty('response')) {
                    return item.response.data
                } else {
                    return item.url
                }
            })
            // 父组件切换uploadedUrl
            let unShowFileList = uploadedList.filter(item => {
                return uploadFileList.indexOf(item) === -1
            }).map(ele => {
                return {
                    name: ele,
                    url: ele
                }
            })
            // 将父组件改变的url放入上传组件
            if (unShowFileList.length <= 0) return
            this.uploadShowFileList = this.uploadShowFileList.concat(unShowFileList)
        }
    }
}
</script>

<style lang="scss" scoped>
// 最大宽度与表单最宽初保持一致
.wrap-upload {
    width: 100%;
}
</style>